package com.yupi.lanhai.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.lanhai.mapper.UserMapper;
import com.yupi.lanhai.model.domain.User;
import com.yupi.lanhai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private UserService userService;

    // 重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "0 8 22 * * *")
    public void doCacheRecommendUser(){
        //设置锁
        RLock lock = redissonClient.getLock("sjf:precachejob:docache:lock");
        try {
            //tryLock：尝试获取锁
            //参数一：等待时间
            //参数二：过期时间，-1表示启动看门狗机制
            if(lock.tryLock(0,-1, TimeUnit.MILLISECONDS)){
                for (Long userId : mainUserList){
                    String redisKey = String.format("sjf:user:recommend:%s", userId);
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> page = new Page<>(1, 20);
                    //todo 分页查询有误，查询的是全的数据
                    Page<User> userPage = userMapper.selectPage(page, queryWrapper);
                    List<User> records = userPage.getRecords();

                    // 写缓存
                    try {
                        redisTemplate.opsForValue().set(redisKey, records, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            // 只能释放自己的锁
            //isHeldByCurrentThread:判断是否是当前自己线程
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }


    }

}
